package org.miaosha.service;

import org.miaosha.mapper.MiaoshaOrderMapper;
import org.miaosha.mapper.OrderInfoMapper;
import org.miaosha.model.*;
import org.miaosha.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author Wrb
 * @date 2019/7/26 17:25
 */
@Service
public class OrderService {

	@Autowired
	private MiaoshaOrderMapper miaoshaOrderMapper;

	@Autowired
	private OrderInfoMapper orderInfoMapper;

	public int insertOrderInfo(OrderInfo orderInfo) {
		return orderInfoMapper.insertSelective(orderInfo);
	}

	public int insertMiaoshaOrder(MiaoshaOrder miaoshaOrder) {
		return miaoshaOrderMapper.insertSelective(miaoshaOrder);
	}

	public MiaoshaOrder getMiaoshaOrderByUserIdAndGoodsId(Long userId, Long goodsId) {
		MiaoshaOrderCriteria criteria = new MiaoshaOrderCriteria();
		criteria.or().andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId);
		List<MiaoshaOrder> miaoshaOrders = miaoshaOrderMapper.selectByExample(criteria);
		if (CollectionUtils.isEmpty(miaoshaOrders)) {
			return null;
		}
		return miaoshaOrders.get(0);
	}

	@Transactional
	public OrderInfo createOrder(MiaoshaUser user, GoodsInfoView goods) {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setCreateDate(new Date());
		orderInfo.setDeliveryAddrId(0L);
		orderInfo.setGoodsCount(1);
		orderInfo.setGoodsId(goods.getId());
		orderInfo.setGoodsName(goods.getGoodsName());
		orderInfo.setGoodsPrice(goods.getGoodsPrice());
		orderInfo.setOrderChannel((byte) 1);
		orderInfo.setStatus((byte) 0);
		orderInfo.setUserId(user.getId());
		Long orderId = SnowflakeIdWorker.generateId();
		orderInfo.setId(orderId);
		int ret = insertOrderInfo(orderInfo);
		if (ret == 0) {
			throw new IllegalArgumentException("插入订单详情失败");
		}
		MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
		miaoshaOrder.setGoodsId(goods.getId());
		miaoshaOrder.setOrderId(orderId);
		miaoshaOrder.setUserId(user.getId());
		int ret1 = insertMiaoshaOrder(miaoshaOrder);
		if (ret1 == 0) {
			throw new IllegalArgumentException("插入秒杀订单失败");
		}
		return orderInfo;
	}
}
